package com.itmuch.box.freemarker.directive;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.itmuch.box.core.PageNative;
import com.itmuch.box.core.constant.ConstantDirective;
import com.itmuch.box.core.dynamicSpec.jpa.PageVo;
import com.itmuch.box.domain.content.vo.ContentDirectiveVo;
import com.itmuch.box.domain.content.vo.ContentVo;
import com.itmuch.box.service.content.ContentService;
import com.itmuch.box.service.sort.SortService;

import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@Component
public class ContentListPageDirective implements TemplateDirectiveModel {
    @Resource
    private ContentService contentService;
    @Resource
    private SortService sortService;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        // 页码
        Integer page = DirectiveUtils.getIntByEnv("page", env);

        // 推荐方式
        Integer recomendId = DirectiveUtils.getInt("recomendId", params);

        // f_model.id 1:文章 2视频
        Integer modelId = DirectiveUtils.getInt("modelId", params);

        // 所属栏目
        Integer categoryId = DirectiveUtils.getInt("categoryId", params);

        // 所属分类
        Integer sortId = DirectiveUtils.getInt("sortId", params);

        Set<Integer> sortIds = null;
        if (sortId != null) {
            sortIds = this.sortService.findChildrenWithSelfIdById(sortId);
        }

        ContentDirectiveVo searchVo = new ContentDirectiveVo();
        searchVo.setCategoryId(categoryId);
        searchVo.setSortIds(sortIds);
        searchVo.setModelId(modelId);
        searchVo.setRecomendId(recomendId);

        PageVo pageVo = new PageVo();
        pageVo.setPage(page);
        pageVo.setOrder("id desc");
        PageNative<ContentVo> pageNative = this.contentService.selectContentVoByConditonPaged(searchVo, pageVo);
        Map<String, Object> map = Maps.newHashMap();
        map.put("content", pageNative);

        TemplateModel wrap = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_23).build().wrap(map);
        env.setVariable(ConstantDirective.CONTENT_LIST_PAGE, wrap);
        body.render(env.getOut());
    }
}
